<template>

    <div>
        <el-popover v-model:visible="visible" ref="poverref" width="800" placement="bottom" trigger="click">
            <template #reference>
                <div style="color: #fff;cursor:pointer" @click="sort"><el-icon>
                        <Sort />
                    </el-icon></div>

            </template>
            <div>
                <div class="sctitle">上传任务 <span>（仅展示本次上传任务）</span></div>
                <div class="filelist">
                    <div class="file-item" v-for="(item, index) in filelist">
                        <div class="fileleft">
                            <div>{{ item.fileName }}</div>
                            <div>
                                <el-progress
                                    v-if="item.status == status.uploading.value || item.status == status.upload_seconds.value || item.status == status.upload_finish.value"
                                    :percentage="item.progress" />
                            </div>
                            <div>{{ status[item.status].desc }} <span v-if="item.status == status.uploading.value">{{
                                sizeMethod.sizetoStr(item.uploadSize) }}/{{ sizeMethod.sizetoStr(item.totalSize)
                                    }}</span>
                            </div>
                        </div>
                        <div>
                            <el-progress type="circle" :width="50" style="margin-right: 10px;"
                                :percentage="item.md5Progress" v-if="item.status == status.init.value" />
                            <img src="../assets/pause.png" @click="pauseclcik(item)"
                                v-if="!item.pause && item.status == status.uploading.value"
                                style="width: 40px;margin-right: 10px;height:40px" alt="" srcset="">
                            <img src="../assets/upload.png" @click="againclick(item)"
                                v-if="item.pause && item.status == status.uploading.value"
                                style="width: 40px;margin-right: 10px;height:40px" alt="" srcset="">
                            <img src="../assets/clean.png" @click="del(item, index)"
                                v-if="item.status == status.upload_finish.value || item.status == status.upload_seconds.value"
                                style="width: 40px;height:40px" alt="" srcset="">
                            <img src="../assets/del.png" @click="del(item, index)"
                                v-if="item.status !== status.upload_finish.value && item.status !== status.init.value && item.status !== status.upload_seconds.value"
                                style="width: 40px;height:40px" alt="" srcset=""></img>


                        </div>
                    </div>
                    <div v-if="filelist.length == 0">
                        <el-empty description="暂无上传任务" />
                    </div>
                </div>
            </div>

            <!-- <span> Some content </span> -->
        </el-popover>
    </div>
</template>
<script setup>
import { ref } from 'vue';
import sizeMethod from "@/utils/utils"
import SparkMD5 from 'spark-md5';
import service from '@/utils/Request';
import { ElMessage } from 'element-plus'
const emit = defineEmits(["getfilelist"])
const filelist = ref([])
const visible = ref(false)
const chunkSize = 1024 * 512;
const dellist = ref([])
const sort = () => {

}
const poverref = ref(null);
const status = {
    emptyfile: {
        value: "emptyfile",
        desc: "文件为空"
    },
    fail: {
        value: "fail",
        desc: "上传失败"
    },
    init: {
        value: "init",
        desc: "解析中"
    },
    uploading: {
        value: "uploading",
        desc: "上传中"
    },
    upload_seconds: {
        value: "upload_seconds",
        desc: "秒传"
    },
    upload_finish: {
        value: "upload_finish",
        desc: "上传完成"
    },
}
const pauseclcik = (item) => {
    item.pause = true
}
const againclick = (item) => {
    item.pause = false;
    uploadFilled(item.uid, item.chunkIndex)
}
const del = (item, index) => {
    dellist.value.push(item.uid)
    filelist.value.splice(index, 1)
}
const open = async (e, pid) => {
    visible.value = true
    let fileitem = {
        file: e.file,
        md5: null,
        md5Progress: 0,
        fileName: e.file.name,
        status: status.init.value,
        chunkIndex: 0,
        progress: 0,
        uploadSize: 0,
        filePid: pid,
        uid: e.file.uid,
        pause: false,
        totalSize: e.file.size,
    }
    //filelist中添加一下
    filelist.value.push(fileitem);
    //如果总大小是0，就是空状态
    if (filelist.totalSize == 0) {
        fileitem.status = status.emptyfile;
        return
    }
    let md5fileUid = await computedMd5(fileitem);
    if (md5fileUid == null) {
        return
    }
    uploadFilled(md5fileUid);



}

//计算md5
const computedMd5 = (fileitem) => {
    let file = fileitem.file;
    let blogSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
    let chunks = Math.ceil(file.size / chunkSize);
    console.log(chunks, "chunks")
    let currentChunk = 0;
    let spark = new SparkMD5.ArrayBuffer();
    let fileReader = new FileReader();
    let loadNext = () => {
        let start = currentChunk * chunkSize;
        let end = start + chunkSize >= file.size ? file.size : start + chunkSize;
        fileReader.readAsArrayBuffer(blogSlice.call(file, start, end))

    }
    loadNext();
    return new Promise((resolve, reject) => {
        let resultFile = getFileByUid(file.uid)
        fileReader.onload = (e) => {
            spark.append(e.target.result)
            currentChunk++;
            if (currentChunk < chunks) {

                let percent = Math.floor((currentChunk / chunks) * 100)
                resultFile.md5Progress = percent;
                loadNext()
            } else {
                let md5 = spark.end();
                spark.destroy()
                resultFile.md5Progress = 100
                resultFile.status = status.uploading.value;
                resultFile.md5 = md5;
                resolve(fileitem.uid)
            }
        }
        fileReader.onerror = () => {
            resultFile.md5Progress = -1
            resultFile.status = status.fail.value
            resolve(fileitem.uid)
        }
    }).catch(e => {
        return null;
    })


}
const getFileByUid = (uid) => {
    let file = filelist.value.find(item => {
        return item.uid === uid
    })
    return file;


}
const uploadFilled = async (md5fileUid, chunkIndex) => {
    chunkIndex = chunkIndex ? chunkIndex : 0;
    let currentfile = getFileByUid(md5fileUid);
    const file = currentfile.file;
    const fileSize = currentfile.totalSize;
    const chunks = Math.ceil(fileSize / chunkSize);
    for (let i = chunkIndex; i < chunks; i++) {
        let delindex = dellist.value.indexOf(md5fileUid);
        if (delindex != -1) {
            dellist.value.splice(delindex, 1);
            break;
        }
        currentfile = getFileByUid(md5fileUid);
        if (currentfile.pause) {
            break;
        }
        let start = i * chunkSize;
        let end = start + chunkSize >= fileSize ? fileSize : start + chunkSize;
        let chunkfile = file.slice(start, end);
        let data = {
            file: chunkfile,
            fileName: currentfile.fileName,
            fileMd5: currentfile.md5,
            chunkIndex: i,
            chunks: chunks,
            fileId: currentfile.fileId,
            filePid: currentfile.filePid,
        }
        let updateResult = await service.post("/file/uploadFile", data);
        currentfile.fileId = updateResult.data.fileId;
        if (updateResult.data.status !== null) {
            currentfile.status = status[updateResult.data.status].value;
        } else {
            currentfile.status = status["fail"].value
            ElMessage({
                type: "warning",
                text: "上传失败，请扩容或联系管理员"
            })
        }
        currentfile.chunkIndex = i;
        currentfile.uploadSize = i * chunkSize;
        currentfile.progress = Math.floor((currentfile.uploadSize / fileSize) * 100);
        if (updateResult.data.status == status.upload_seconds.value || updateResult.data.status == status.upload_finish.value) {
            currentfile.progress = 100
            break;
        }
    }
    emit("getfilelist")


}
defineExpose({
    open
})
</script>
<style>
.sctitle {
    font-size: 15px;
    border-bottom: 1px solid #e5e5e5;
}

.filelist {
    width: 100%;
    min-height: 50vh;
    padding: 10px;
    box-sizing: border-box;
}

.file-item {
    width: 100%;
    height: auto;
    display: flex;
    justify-content: space-between;
}

.fileleft {
    width: 80%;
}
</style>